﻿using DevExpress.XtraEditors;
using DLL;
using NursingDocumentInfoSystem.Model;
using NursingFormSystem;
using NursingFormSystem.BLL;
using NursingFormSystem.Common;
using NursingFormSystem.Model;
using NursingFormSystem.NursingEntry;
using SQLDLL;
using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace NursingDocumentInfoSystem
{
    public partial class NursingForm : XtraForm
    {
        #region 变量声明
        public Tb_User LoginUser;
        public PatientInfo PatientInfo;
        public DataTable PName;
        bool continueflag;
        int continuenum = 0;
        DataTable IOData;
        string[] UserParam, patients;
        #endregion

        #region 构造函数
        public NursingForm(string[] loginUser, string[] patientInfo)
        {
            InitializeComponent();
            this.UserParam = loginUser;
            this.patients = patientInfo;
            this.PatientInfo = ArrayToObject.ArrayToPatientInfo(patientInfo);
            this.LoginUser = ArrayToObject.ArrayToLoginUser(loginUser);
            continueflag = false;
            ccb_printType.SelectedIndex = 1;//默认打印本科室护理记录点
        }
        #endregion

        #region 窗体加载
        private void NursingForm_Load(object sender, EventArgs e)
        {
            bandedGridView1.OptionsView.ShowColumnHeaders = false;
            dateE_StartTime.DateTime = System.DateTime.Now.AddDays(-30).Date;
            dateE_EndTime.DateTime = System.DateTime.Now;
            bandedGridView1.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;   //是否显示过滤面板
            bandedGridView1.OptionsCustomization.AllowFilter = false;                      //是否允许过滤
            bandedGridView1.Appearance.Row.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            bandedGridView1.OptionsCustomization.AllowColumnMoving = false;
            bandedGridView1.OptionsBehavior.Editable = false;
            bandedGridView1.OptionsCustomization.AllowSort = false;
            bandedGridView1.OptionsView.ColumnAutoWidth = false;
            bandedGridView1.BestFitColumns();
            bandedGridView1.HorzScrollVisibility = DevExpress.XtraGrid.Views.Base.ScrollVisibility.Always;
            bandedGridView1.VertScrollVisibility = DevExpress.XtraGrid.Views.Base.ScrollVisibility.Always;
            bandedGridView1.MouseDown += BandedGridView1_MouseDown;
            LoadOldPatients();
        }
        #endregion

        #region BandedGridView1
        private void BandedGridView1_CalcRowHeight(object sender, DevExpress.XtraGrid.Views.Grid.RowHeightEventArgs e)
        {
            if (e.RowHandle >= 0)
                e.RowHeight = 35;
        }

        private void BandedGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hInfo = bandedGridView1.CalcHitInfo(new Point(e.X, e.Y));
            if (e.Button == MouseButtons.Left && e.Clicks == 2)
            {
                if (hInfo.InRow)//判断光标是否在行范围内 
                {
                    if (hInfo.Column != null && hInfo.Column.Name == "bandedGridColumn15")
                    {
                        string value = bandedGridView1.GetDataRow(hInfo.RowHandle)[14] + "";
                        if (value.StartsWith("统计范围"))
                        {
                            int num = bandedGridView1.GetSelectedRows()[0];
                            string id = bandedGridView1.GetRowCellValue(num, "ID").ToString();
                            if (string.IsNullOrEmpty(id)) return;
                            if (id.EndsWith("024") || id.EndsWith("012")) return;
                            if (id.IndexOf("-") > 0 && id.Split('-').Length == 3)
                            {
                                //重新编辑自定义统计
                                NursingSummaryHours frm = new NursingSummaryHours(id);
                                frm.ShowDialog();
                                if (frm.DialogResult != DialogResult.OK) return;
                                //return data:
                                string date = frm.Date;
                                string stime = frm.Stime;
                                string etime = frm.Etime;
                                TimeSpan _etime = DateTime.Parse(etime).TimeOfDay;
                                TimeSpan _stime = DateTime.Parse(stime).TimeOfDay;
                                int hours = (_etime.Hours - _stime.Hours);
                                if (hours >= 0) hours += 1;
                                if (hours < 0) hours = 24 + hours + 1;
                                string sqldefault = @"if(EXISTS (SELECT Id FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  ))
                            BEGIN UPDATE NursingFormSumIO SET  GroupDiy ='{12}',BeginTime='{11}' WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  END ELSE BEGIN
                            INSERT INTO NursingFormSumIO (PatientId,VisitId,SumDate,PatientName,BedNo,DepartmentId,DepartmentName,AreaId,AreaName,FormId,FormName,Group12,Group24,BeginTime,GroupDiy)
                            VALUES('{0}','{1}','{2}' ,'{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',NULL,NULL,'{11}','{12}') END";
                                sqldefault = string.Format(sqldefault, this.PatientInfo.PATIENT_ID, this.PatientInfo.VISIT_ID, date, this.PatientInfo.PATIENT_NAME, this.PatientInfo.BED_NO, this.PatientInfo.DEPARTMENT_ID, this.PatientInfo.DEPARTMENT_NAME, this.PatientInfo.NURSE_CELL_CODE, this.PatientInfo.NURSE_CELL_NAME, (int)FormType.TempbedNursing, EnumHelper.GetDescription(FormType.TempbedNursing), stime, hours);
                                SqlHelper.ExecuteNonQuery(sqldefault);
                                LoadOldPatients();
                                MessageBox.Show("操作成功");
                                return;
                            }
                        }
                        Clipboard.SetDataObject(value);
                        XtraMessageBox.Show("已复制到剪切板");
                    }
                    else
                    {
                        btn_Update_Click(null, null);
                    }
                }
            }
        }
        #endregion

        #region 新增
        private void btn_Add_Click(object sender, EventArgs e)
        {
            NusingEntryForm NEF = new NusingEntryForm(UserParam, patients, "-1");
            NEF.ShowDialog();
            LoadOldPatients();
        }
        #endregion

        #region 查询
        private void btn_Query_Click(object sender, EventArgs e)
        {
            LoadOldPatients();
        }
        #endregion

        #region 护理单打印
        private void btn_PrintView_Click(object sender, EventArgs e)
        {
            if (bandedGridView1.RowCount == 0)
            {
                XtraMessageBox.Show("没有要打印的条目哦");
                return;
            }

            string[] ID = new string[bandedGridView1.RowCount];
            for (int i = 0; i < bandedGridView1.RowCount; i++)
            {
                string areaId = bandedGridView1.GetDataRow(i)["AreaId"].ToString();
                if (ccb_printType.SelectedItem == "本科室" && areaId == LoginUser.DepartmentCode)
                    ID[i] = bandedGridView1.GetDataRow(i)["ID"].ToString();
                if (ccb_printType.SelectedItem == "全部")
                    ID[i] = bandedGridView1.GetDataRow(i)["ID"].ToString();
            }
            NursingPrint print = new NursingPrint(ID, LoginUser, patients, dateE_StartTime.DateTime, dateE_EndTime.DateTime, continueflag, continuenum);
            print.Show();
            continueflag = false;
        }
        #endregion

        #region 删除
        private void btn_Del_Click(object sender, EventArgs e)
        {
            if (bandedGridView1.FocusedRowHandle <= 0) return;
            int num = bandedGridView1.GetSelectedRows()[0];
            string id = bandedGridView1.GetRowCellValue(num, "ID").ToString();
            if (!RegexHelper.IsInt32(id)) return;
            if (XtraMessageBox.Show("确定要删除吗？", "删除询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) return;
            string delete = @"use BNNursingDocsSystem_Develop ; update t_ClinicalNursing set 
                  [PatientId] =  [PatientId] +'删除'
                 ,[Updatetime] = '" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + @"'
                ,[UpdateuserId] = '" + LoginUser.UserId + @"'
                ,[UpdateuserName] = '" + LoginUser.UserName + @"'            
                  WHERE Id='" + id + "'";
            int key = SqlHelper.ExecuteNonQuery(CommandType.Text, delete);
            if (key > 0)
            {
                XtraMessageBox.Show("删除成功");
                #region 上传海泰
                if (Base.ESSwitchHT == "1")
                {
                    SynchroBLL synchro = new SynchroBLL();
                    ClinicalNursinguser cn = new ClinicalNursinguser();
                    cn.PatientId = bandedGridView1.GetRowCellValue(num, "PatientId").ToString();
                    cn.PatientName = bandedGridView1.GetRowCellValue(num, "PatientName").ToString();
                    cn.data = bandedGridView1.GetRowCellValue(num, "data").ToString();
                    cn.Updatetime = System.DateTime.Now;
                    cn.UpdateuserId = LoginUser.UserId;
                    cn.UpdateuserName = LoginUser.UserName;
                    cn.DepId = LoginUser.DepartmentCode;
                    cn.DepName = LoginUser.DepartmentName;
                    string syncSN_Sql = string.Format("SELECT syncSN FROM dbo.t_ClinicalNursing(NOLOCK) WHERE id = {0}", id);
                    string syncSN = SqlHelper.ExecuteDataset(syncSN_Sql, CommandType.Text).Tables[0].Rows[0][0] + "";
                    cn.syncSN = syncSN;
                    synchro.clinicalNursingInfoAsyncToEMRDelegateMethod(cn, "002", "3");
                }
                #endregion

                LoadOldPatients();
            }
            else
            {
                XtraMessageBox.Show("删除失败");
            }
        }
        #endregion

        #region 修改
        private void btn_Update_Click(object sender, EventArgs e)
        {
            int[] select = bandedGridView1.GetSelectedRows();
            if (select.Length == 0) return;
            int num = bandedGridView1.GetSelectedRows()[0];
            string id = bandedGridView1.GetRowCellValue(num, "ID").ToString();
            if (string.IsNullOrEmpty(id)) return;
            if (id.IndexOf("-") > 0 && id.Split('-').Length == 3 && !id.EndsWith("024") && !id.EndsWith("012"))
            {
                //重新编辑自定义统计
                NursingSummaryHours frm = new NursingSummaryHours(id);
                frm.ShowDialog();
                if (frm.DialogResult != DialogResult.OK) return;
                //return data:
                string date = frm.Date;
                string stime = frm.Stime;
                string etime = frm.Etime;
                TimeSpan _etime = DateTime.Parse(etime).TimeOfDay;
                TimeSpan _stime = DateTime.Parse(stime).TimeOfDay;
                int hours = (_etime.Hours - _stime.Hours);
                if (hours >= 0) hours += 1;
                if (hours < 0) hours = 24 + hours + 1;
                string sqldefault = @"if(EXISTS (SELECT Id FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  ))
                            BEGIN UPDATE NursingFormSumIO SET  GroupDiy ='{12}',BeginTime='{11}' WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  END ELSE BEGIN
                            INSERT INTO NursingFormSumIO (PatientId,VisitId,SumDate,PatientName,BedNo,DepartmentId,DepartmentName,AreaId,AreaName,FormId,FormName,Group12,Group24,BeginTime,GroupDiy)
                            VALUES('{0}','{1}','{2}' ,'{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',NULL,NULL,'{11}','{12}') END";
                sqldefault = string.Format(sqldefault, this.PatientInfo.PATIENT_ID, this.PatientInfo.VISIT_ID, date, this.PatientInfo.PATIENT_NAME, this.PatientInfo.BED_NO, this.PatientInfo.DEPARTMENT_ID, this.PatientInfo.DEPARTMENT_NAME, this.PatientInfo.NURSE_CELL_CODE, this.PatientInfo.NURSE_CELL_NAME, (int)FormType.TempbedNursing, EnumHelper.GetDescription(FormType.TempbedNursing), stime, hours);
                SqlHelper.ExecuteNonQuery(sqldefault);
                LoadOldPatients();
                MessageBox.Show("操作成功");
                return;
            }
            string SecondSelect = string.Format(@"SELECT * FROM [BNNursingDocsSystem_Develop].[dbo].[V_YDHL_PATIENT](NOLOCK) WHERE  PATIENT_ID = '{0}' and VISIT_ID ='{1}'", PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID);
            DataTable Patients = SqlHelper.ExecuteDataset(SecondSelect, CommandType.Text).Tables[0];
            if (Patients.Rows.Count <= 0) return;
            if (string.IsNullOrEmpty(id) || !Regex.IsMatch(id, @"^\d+$")) return;
            NusingEntryForm NEF = new NusingEntryForm(UserParam, patients, id);
            NEF.ShowDialog();
            LoadOldPatients();
        }
        #endregion

        #region 护理记录查询
        private void GetNursingRecord(string selectsql)
        {
            #region 组装DataTable
            DataTable selectNursingForm = SqlHelper.ExecuteDataset(selectsql, CommandType.Text).Tables[0];
            string failId = string.Empty;
            if (selectNursingForm.Rows.Count > 0)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("Date", typeof(string));//日期
                dt.Columns.Add("Time", typeof(string));//时间
                dt.Columns.Add("Temper", typeof(string));//体温
                dt.Columns.Add("Pulse", typeof(string));//脉搏
                dt.Columns.Add("HeartRate", typeof(string));//心率
                dt.Columns.Add("Breath", typeof(string));//呼吸
                dt.Columns.Add("BloodPressure", typeof(string));//血压
                dt.Columns.Add("Spo2", typeof(string));//血氧饱和度
                dt.Columns.Add("StandUp", typeof(string));//翻身
                dt.Columns.Add("Intakename", typeof(string));//输入名称
                dt.Columns.Add("Intakevalue", typeof(string));//输入量
                dt.Columns.Add("Intakediway", typeof(string));//途径
                dt.Columns.Add("Dischargename", typeof(string));//排出名称
                dt.Columns.Add("Dischargevalue", typeof(string));//排出量
                dt.Columns.Add("Tendcontent", typeof(string));//病情及护理措施
                dt.Columns.Add("NursName", typeof(string));//签名
                dt.Columns.Add("ID", typeof(string));//ID
                dt.Columns.Add("PatientId", typeof(string));
                dt.Columns.Add("PatientName", typeof(string));
                dt.Columns.Add("data", typeof(string));
                dt.Columns.Add("AreaId", typeof(string));
                dt.Columns.Add("SumInValue", typeof(string)); //本次总入量
                dt.Columns.Add("SumOutValue", typeof(string));//本次总出量
                dt.Columns.Add("SumFlag12", typeof(string));//具有统计12小时的标识，为后续合并设置提供标识
                dt.Columns.Add("SumFlag24", typeof(string));//具有统计24小时的标识，为后续合并设置提供标识

                for (int i = 0; i < selectNursingForm.Rows.Count; i++)
                {
                    ClinicalNursing cn = XmlUtil.XMLToObject<ClinicalNursing>(selectNursingForm.Rows[i]["data"] + "", Encoding.UTF8);
                    string date = selectNursingForm.Rows[i]["Date"] + "";
                    string time = selectNursingForm.Rows[i]["Time"] + "";
                    string nursName = selectNursingForm.Rows[i]["NursName"] + "";
                    string id = selectNursingForm.Rows[i]["ID"] + "";
                    string PatientId = selectNursingForm.Rows[i]["PatientId"] + "";
                    string PatientName = selectNursingForm.Rows[i]["PatientName"] + "";
                    string bloodPressure = "";
                    string areaId = selectNursingForm.Rows[i]["AreaId"] + "";
                    string suminvalue = "";
                    string sumoutvalue = "";
                    float tempinput = 0;
                    if (cn == null) { failId += string.Format("{0},", id); continue; }
                    if (cn.Intakevalue.Contains(","))
                    {
                        string[] str = cn.Intakevalue.Split(',');
                        for (int j = 0; j < str.Length; j++)
                        {
                            if (RegexHelper.IsFloat(str[j]))
                            {
                                tempinput = tempinput + Convert.ToSingle(str[j]);
                            }
                        }
                        suminvalue = Convert.ToString(tempinput);
                    }
                    else
                    {
                        suminvalue = cn.Intakevalue;
                    }
                    float tempout = 0;
                    if (cn.Dischargevalue.Contains(","))
                    {
                        string[] str = cn.Dischargevalue.Split(',');
                        for (int j = 0; j < str.Length; j++)
                        {
                            if (RegexHelper.IsFloat(str[j]))
                            {
                                tempout = tempout + Convert.ToSingle(str[j]);
                            }
                        }
                        sumoutvalue = Convert.ToString(tempout);
                    }
                    else
                    {
                        sumoutvalue = cn.Dischargevalue;
                    }
                    //高压cn.Systolicpressure
                    //低压cn.Diastolicpressure
                    if (cn != null)
                    {
                        bloodPressure = cn.Systolicpressure + "/" + cn.Diastolicpressure;
                        string data = selectNursingForm.Rows[i]["data"] + "";
                        DataRow row = dt.NewRow();
                        row["Date"] = date;//日期
                        row["Time"] = time;//时间
                        row["Temper"] = cn.Temper;//体温
                        row["Pulse"] = cn.Pulse;//脉搏
                        row["HeartRate"] = cn.HeartRate;//心率
                        row["Breath"] = cn.Breath;//呼吸
                        row["BloodPressure"] = bloodPressure.Trim().Equals("/") ? string.Empty : bloodPressure;//血压
                        row["Spo2"] = cn.Spo2;//血氧饱和度
                        row["StandUp"] = cn.StandUp;//翻身
                        row["Intakename"] = cn.Intakename;//输入名称
                        row["Intakevalue"] = cn.Intakevalue;//输入量
                        row["Intakediway"] = cn.Intakediway;//途径
                        row["Dischargename"] = cn.Dischargename;//排出名称
                        row["Dischargevalue"] = cn.Dischargevalue;//排出量
                        row["Tendcontent"] = StringHelpers.OutputDecode(cn.Tendcontent);//病情及护理措施
                        row["NursName"] = nursName;//签名
                        row["ID"] = id;//ID
                        row["PatientId"] = PatientId;
                        row["PatientName"] = PatientName;
                        row["data"] = data;
                        row["AreaId"] = areaId;
                        row["SumInValue"] = suminvalue; //本次总入量
                        row["SumOutValue"] = sumoutvalue;//本次总出量
                        row["SumFlag12"] = "";//具有统计12小时的标识，为后续合并设置提供标识
                        row["SumFlag24"] = "";//具有统计24小时的标识，为后续合并设置提供标识
                        dt.Rows.Add(row);
                    }
                }


                #region 获得出入量统计的部分，然后加以添加相关行
                dt.DefaultView.Sort = "Date asc,Time asc";
                dt = dt.DefaultView.ToTable();
                GetSumIO();
                DataTable tempdt = dt.Clone();
                if (IOData.Rows.Count > 0)
                {
                    for (int j = 0; j < IOData.Rows.Count; j++)
                    {
                        if (IOData.Rows[j]["Group12"].ToString().Contains("Y")) //是否有12小时的统计标识
                        {
                            float invalue = 0f;
                            float outvalue = 0f;
                            for (int m = 0; m < dt.Rows.Count; m++)
                            {
                                if (Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd").Contains(Convert.ToDateTime(dt.Rows[m]["Date"]).ToString("yyyy-MM-dd")))//同一天日期
                                {
                                    string _strtime1 = "7:01";
                                    string _strtime2 = "19:00";
                                    TimeSpan dsptime1 = DateTime.Parse(_strtime1).TimeOfDay;
                                    TimeSpan dsptime2 = DateTime.Parse(_strtime2).TimeOfDay;
                                    TimeSpan dspnow = DateTime.Parse(dt.Rows[m]["Time"].ToString()).TimeOfDay;
                                    if ((dspnow >= dsptime1) && (dspnow <= dsptime2))
                                    {
                                        if (RegexHelper.IsFloat(dt.Rows[m]["SumInValue"]))
                                        {
                                            invalue = invalue + Convert.ToSingle(dt.Rows[m]["SumInValue"].ToString());
                                        }
                                        if (RegexHelper.IsFloat(dt.Rows[m]["SumOutValue"]))
                                        {
                                            outvalue = outvalue + Convert.ToSingle(dt.Rows[m]["SumOutValue"].ToString());
                                        }
                                    }
                                }
                            }
                            string suminvalue = Convert.ToString(invalue);
                            string sumoutvalue = Convert.ToString(outvalue);
                            string date12 = Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd");

                            DataRow row = tempdt.NewRow();
                            row["Date"] = date12;//日期
                            row["Time"] = "19:01";//时间
                            row["Temper"] = suminvalue;//体温
                            row["Pulse"] = "12小时总出量:";//脉搏
                            row["HeartRate"] = sumoutvalue;//心率
                            row["Breath"] = "";//呼吸
                            row["BloodPressure"] = "";//血压
                            row["Spo2"] = "";//血氧饱和度
                            row["StandUp"] = "";//翻身
                            row["Intakename"] = "";//输入名称
                            row["Intakevalue"] = "";//输入量
                            row["Intakediway"] = "";//途径
                            row["Dischargename"] = "";//排出名称
                            row["Dischargevalue"] = "";//排出量
                            row["Tendcontent"] = "统计范围:" + date12 + " 07:01至19:00";//病情及护理措施
                            row["NursName"] = "";//签名
                            row["ID"] = Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd 07:00:00.012");//ID
                            row["PatientId"] = "";
                            row["PatientName"] = "";
                            row["data"] = "";
                            row["AreaId"] = "12小时总入量:";
                            row["SumInValue"] = suminvalue; //本次总入量
                            row["SumOutValue"] = sumoutvalue;//本次总出量
                            row["SumFlag12"] = "Y";//具有统计12小时的标识，为后续合并设置提供标识
                            row["SumFlag24"] = "";//具有统计24小时的标识，为后续合并设置提供标识
                            tempdt.Rows.Add(row);
                        }

                        if (IOData.Rows[j]["Group24"].ToString().Contains("Y")) //是否有24小时的统计标识
                        {
                            float invalue = 0f;
                            float outvalue = 0f;
                            string valueof24_1 = "1980-01-01";
                            for (int m = 0; m < dt.Rows.Count; m++)
                            {
                                if (valueof24_1.Contains(dt.Rows[m]["Date"].ToString()))
                                {
                                    string _strtime1 = "7:00";
                                    TimeSpan dsptime1 = DateTime.Parse(_strtime1).TimeOfDay;
                                    TimeSpan dspnow = DateTime.Parse(dt.Rows[m]["Time"].ToString()).TimeOfDay;
                                    if (dspnow <= dsptime1)
                                    {
                                        if (RegexHelper.IsFloat(dt.Rows[m]["SumInValue"]))
                                        {
                                            invalue = invalue + Convert.ToSingle(dt.Rows[m]["SumInValue"].ToString());
                                        }
                                        if (RegexHelper.IsFloat(dt.Rows[m]["SumOutValue"]))
                                        {
                                            outvalue = outvalue + Convert.ToSingle(dt.Rows[m]["SumOutValue"].ToString());
                                        }
                                    }
                                }
                                else if (Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd").Contains(Convert.ToDateTime(dt.Rows[m]["Date"]).ToString("yyyy-MM-dd")))//同一天日期
                                {
                                    string _strtime1 = "7:01";
                                    TimeSpan dsptime1 = DateTime.Parse(_strtime1).TimeOfDay;
                                    TimeSpan dspnow = DateTime.Parse(dt.Rows[m]["Time"].ToString()).TimeOfDay;
                                    if (dspnow >= dsptime1)
                                    {
                                        if (RegexHelper.IsFloat(dt.Rows[m]["SumInValue"]))
                                        {
                                            invalue = invalue + Convert.ToSingle(dt.Rows[m]["SumInValue"].ToString());
                                        }
                                        if (RegexHelper.IsFloat(dt.Rows[m]["SumOutValue"]))
                                        {
                                            outvalue = outvalue + Convert.ToSingle(dt.Rows[m]["SumOutValue"].ToString());
                                        }
                                    }
                                    DateTime tempdt01 = Convert.ToDateTime(dt.Rows[m]["Date"].ToString());
                                    valueof24_1 = tempdt01.AddDays(1).ToString("yyyy-MM-dd");
                                }
                            }
                            string suminvalue = Convert.ToString(invalue);
                            string sumoutvalue = Convert.ToString(outvalue);
                            string date24 = Convert.ToDateTime(IOData.Rows[j]["SumDate"]).AddDays(1).ToString("yyyy-MM-dd");//显示第2天的日期
                            DataRow row = tempdt.NewRow();
                            row["Date"] = date24;//日期
                            row["Time"] = "07:01";//时间
                            row["Temper"] = suminvalue;//体温
                            row["Pulse"] = "24小时总出量:";//脉搏
                            row["HeartRate"] = sumoutvalue;//心率
                            row["Breath"] = "";//呼吸
                            row["BloodPressure"] = "";//血压
                            row["Spo2"] = "";//血氧饱和度
                            row["StandUp"] = "";//翻身
                            row["Intakename"] = "";//输入名称
                            row["Intakevalue"] = "";//输入量
                            row["Intakediway"] = "";//途径
                            row["Dischargename"] = "";//排出名称
                            row["Dischargevalue"] = "";//排出量
                            row["Tendcontent"] = "统计范围:" + Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd 07:01至") + Convert.ToDateTime(IOData.Rows[j]["SumDate"]).AddDays(1).ToString("yyyy-MM-dd 07:00");//病情及护理措施
                            row["NursName"] = "";//签名
                            row["ID"] = Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd 07:00:00.024");//ID
                            row["PatientId"] = "";
                            row["PatientName"] = "";
                            row["data"] = "";
                            row["AreaId"] = "24小时总入量:";
                            row["SumInValue"] = suminvalue; //本次总入量
                            row["SumOutValue"] = sumoutvalue;//本次总出量
                            row["SumFlag12"] = "";//具有统计12小时的标识，为后续合并设置提供标识
                            row["SumFlag24"] = "Y";//具有统计24小时的标识，为后续合并设置提供标识
                            tempdt.Rows.Add(row);
                        }
                        #region 对自定义统计进行逻辑计算
                        object groupDiy = IOData.Rows[j]["GroupDiy"];
                        object beginTime = IOData.Rows[j]["BeginTime"];
                        object sumDate = IOData.Rows[j]["SumDate"];
                        if (groupDiy != DBNull.Value && groupDiy != null && Convert.ToInt32(groupDiy) > 0) //是否有自定义的统计标识
                        {
                            float invalue = 0f;
                            float outvalue = 0f;
                            string valueofDiyDate = "1980-01-01";
                            int maxHours = Convert.ToInt32(groupDiy);
                            string _strtime1 = beginTime.ToString();
                            if (string.IsNullOrEmpty(_strtime1)) _strtime1 = "07:01";
                            DateTime maxtime = DateTime.Parse(valueofDiyDate + " " + _strtime1).AddHours(maxHours);//统计结束时间
                            bool nextDay = false;
                            if (maxtime.Day == 2) nextDay = true;
                            TimeSpan dsptime1 = DateTime.Parse(_strtime1).TimeOfDay;//统计起始时间
                            for (int m = 0; m < dt.Rows.Count; m++)
                            {
                                string date = Convert.ToDateTime(dt.Rows[m]["Date"]).ToString("yyyy-MM-dd");//护理日期
                                TimeSpan dspnow = DateTime.Parse(dt.Rows[m]["Time"].ToString()).TimeOfDay;//护理时间
                                //同一天日期 或者 第二天日期
                                if (Convert.ToDateTime(sumDate).ToString("yyyy-MM-dd").Contains(date) || (nextDay && Convert.ToDateTime(sumDate).AddDays(1).ToString("yyyy-MM-dd").Contains(date)))
                                {
                                    DateTime itemTime = Convert.ToDateTime(date).AddHours(dspnow.Hours).AddMinutes(dspnow.Minutes);//护理完整时间
                                    maxtime = Convert.ToDateTime(Convert.ToDateTime(sumDate).ToString("yyyy-MM-dd") + " " + _strtime1).AddHours(maxHours);//完整统计结束时间
                                    DateTime fullBeginTime = Convert.ToDateTime(Convert.ToDateTime(sumDate).ToString("yyyy-MM-dd") + " " + _strtime1);//完整统计开始时间
                                    //完整护理时间 介于 完整统计开始时间和完整统计结束时间即为统计
                                    if (itemTime >= (fullBeginTime) && (itemTime <= maxtime))
                                    {
                                        if (RegexHelper.IsFloat(dt.Rows[m]["SumInValue"]))
                                        {
                                            invalue = invalue + Convert.ToSingle(dt.Rows[m]["SumInValue"]);
                                        }
                                        if (RegexHelper.IsFloat(dt.Rows[m]["SumOutValue"].ToString()))
                                        {
                                            outvalue = outvalue + Convert.ToSingle(dt.Rows[m]["SumOutValue"]);
                                        }
                                    }
                                    DateTime tempdt01 = Convert.ToDateTime(date);
                                    valueofDiyDate = tempdt01.AddDays(1).ToString("yyyy-MM-dd");
                                }
                            }
                            string suminvalue = Convert.ToString(invalue);
                            string sumoutvalue = Convert.ToString(outvalue);
                            string dateDiy = Convert.ToDateTime(sumDate).AddHours(dsptime1.Hours).AddMinutes(dsptime1.Minutes).AddHours(maxHours).ToString("yyyy-MM-dd");

                            DataRow row = tempdt.NewRow();
                            row["Date"] = dateDiy;//日期
                            row["Time"] = DateTimeHelper.HHmmssToHHmm(maxtime.AddMinutes(1).ToString("HH:mm"));//时间
                            row["Temper"] = suminvalue;//体温
                            row["Pulse"] = maxHours + "小时总出量";//脉搏
                            row["HeartRate"] = sumoutvalue;//心率
                            row["Breath"] = "";//呼吸
                            row["BloodPressure"] = "";//血压
                            row["Spo2"] = "";//血氧饱和度
                            row["StandUp"] = "";//翻身
                            row["Intakename"] = "";//输入名称
                            row["Intakevalue"] = "";//输入量
                            row["Intakediway"] = "";//途径
                            row["Dischargename"] = "";//排出名称
                            row["Dischargevalue"] = "";//排出量
                            row["Tendcontent"] = "统计范围:" + Convert.ToDateTime(sumDate).ToString("yyyy-MM-dd ") + beginTime + "至" + Convert.ToDateTime(sumDate).AddHours(dsptime1.Hours).AddMinutes(dsptime1.Minutes).AddHours(maxHours).ToString("yyyy-MM-dd HH:mm:ss");//病情及护理措施
                            row["NursName"] = "";//签名
                            row["ID"] = Convert.ToDateTime(Convert.ToDateTime(sumDate).ToString("yyyy-MM-dd") + " " + beginTime).AddMilliseconds(Convert.ToInt32(groupDiy)).ToString("yyyy-MM-dd HH:mm:ss.fff");//ID
                            row["PatientId"] = "";
                            row["PatientName"] = "";
                            row["data"] = "";
                            row["AreaId"] = maxHours + "小时总入量:";
                            row["SumInValue"] = suminvalue; //本次总入量
                            row["SumOutValue"] = sumoutvalue;//本次总出量
                            row["SumFlag12"] = "";//具有统计12小时的标识，为后续合并设置提供标识
                            row["SumFlag24"] = "Y";//具有统计24小时的标识，为后续合并设置提供标识
                            tempdt.Rows.Add(row);

                        }
                        #endregion
                    }
                }
                #endregion

                //将tempdt添加到dt中
                for (int n = 0; n < tempdt.Rows.Count; n++)
                {
                    DataRow dr = dt.NewRow();
                    dr = tempdt.Rows[n];
                    dt.Rows.Add(dr.ItemArray);
                }
                dt.DefaultView.Sort = "Date desc,Time desc";
                dt = dt.DefaultView.ToTable();
                gridControl1.DataSource = dt;
                gridControl1.ForceInitialize();
                if (!string.IsNullOrEmpty(failId))
                    MessageBox.Show("以下ID数据加载失败:" + failId);
            }
            else
            {
                gridControl1.DataSource = selectNursingForm;
            }
            bandedGridView1.TopRowIndex = topIndex;//解决dev GridControl刷新数据后，滚动条恢复原来位置
            #endregion
        }

        private void GetSumIO()
        {
            string sql = @"SELECT SumDate,Group12,Group24,GroupDiy,BeginTime FROM [BNNursingDocsSystem_Develop].[dbo].[NursingFormSumIO](NOLOCK) where PatientId ='{0}' AND VisitId='{1}' AND FormId='{2}' ORDER BY SumDate";
            sql = string.Format(sql, PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID, (int)FormType.TempbedNursing);
            IOData = new DataTable();
            IOData = SqlHelper.ExecuteDataset(sql, CommandType.Text).Tables[0];
        }
        #endregion

        #region 加载历史病人
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            pnlHisPatiens.Visible = false;
            ChooseOutPatiens c = new ChooseOutPatiens(UserParam);
            c.ShowDialog();
            if (c.DialogResult == DialogResult.Yes)
            {
                PatientInfo.PATIENT_ID = c.PatientID;
                PatientInfo.VISIT_ID = Convert.ToInt32(c.VisitID);
                if (ChooseOutPatiens.ReturnPatientEntity.PatientName != null)
                {
                    pnlHisPatiens.Visible = !true;
                    labelName.Text = ChooseOutPatiens.ReturnPatientEntity.PatientName;
                    labelSex.Text = ChooseOutPatiens.ReturnPatientEntity.Sex;
                    labelPatientID.Text = ChooseOutPatiens.ReturnPatientEntity.PatientID;
                    labelInDate.Text = ChooseOutPatiens.ReturnPatientEntity.InDate;
                    labelBed.Text = ChooseOutPatiens.ReturnPatientEntity.BedNo;
                    lblVisitID.Text = PatientInfo.VISIT_ID.ToString();
                    LoadOldPatients();
                }
            }
        }
        #endregion

        #region 加载在院病人
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            pnlHisPatiens.Visible = false;
        }
        #endregion

        #region bandedGridView1 数据源
        public void LoadOldPatients()
        {
            if (dateE_EndTime.Text.Equals("1980-10-01"))
            {
                dateE_EndTime.Text = System.DateTime.Now.ToString("yyyy-MM-dd");
            }
            StringBuilder sql = new StringBuilder();
            sql.Append("SELECT [ID],[PatientId],[VISIT_ID],[PatientName],[DepId],[DepName],[AreaId],[AreaName],[Date],[Time],[data],[NursName],[Submittime],[SubmituserId],[SubmituserName],[Updatetime],[UpdateuserId],[UpdateuserName],[syncSN] FROM [BNNursingDocsSystem_Develop].[dbo].[t_ClinicalNursing](NOLOCK) ");
            sql.AppendFormat(" WHERE PatientId ='{0}' AND VISIT_ID ='{1}' AND Date BETWEEN '{2}' AND '{3}' ", PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID, dateE_StartTime.Text, dateE_EndTime.Text);
            if (ccb_printType.SelectedItem == "本科室")
                sql.AppendFormat(" AND AreaId='{0}'", LoginUser.DepartmentCode);
            sql.Append(" ORDER BY CONVERT(DATETIME,Date+' '+Time,120) DESC");
            GetNursingRecord(sql.ToString());
        }
        #endregion

        #region 解决dev GridControl刷新数据后，滚动条恢复原来位置
        int topIndex = -1;
        private void bandedGridView1_TopRowChanged(object sender, EventArgs e)
        {
            topIndex = bandedGridView1.TopRowIndex;
        }
        #endregion

        #region 续打所需的功能
        //续打所需的功能
        private void ContinuePrint()
        {
            continueflag = true;//续打标识
            int[] select = bandedGridView1.GetSelectedRows();
            if (select.Length == 0)
            {
                return;
            }
            continuenum = bandedGridView1.GetSelectedRows()[0];//倒序的行数
            MessageBox.Show("添加续打成功");
        }

        private void ToolStripMenuItemContinuePrint_Click(object sender, EventArgs e)
        {
            ContinuePrint();
        }
        #endregion

        #region 统计
        private void ToolStripMenuItem12_Click(object sender, EventArgs e)
        {
            SumData(12, "07:01");
        }

        private void ToolStripMenuItem24_Click(object sender, EventArgs e)
        {
            SumData(24, "07:01");
        }

        private void ToolStripMenuItemDiy_Click(object sender, EventArgs e)
        {
            int[] select = bandedGridView1.GetSelectedRows();
            if (select.Length == 0) return;
            int num = bandedGridView1.GetSelectedRows()[0];
            string date = bandedGridView1.GetRowCellValue(num, "Date").ToString();
            string etime = bandedGridView1.GetRowCellValue(num, "Time").ToString();
            string stime = "07:01";
            NursingSummaryHours frm = new NursingSummaryHours(date, stime, etime);
            frm.ShowDialog();
            if (frm.DialogResult != System.Windows.Forms.DialogResult.OK) return;
            //return data:
            date = frm.Date;
            stime = frm.Stime;
            etime = frm.Etime;

            TimeSpan _etime = DateTime.Parse(etime).TimeOfDay;
            TimeSpan _stime = DateTime.Parse(stime).TimeOfDay;
            int hours = (_etime.Hours - _stime.Hours);
            if (hours >= 0) hours += 1;
            if (hours < 0) hours = 24 + hours + 1;
            SumData(hours, stime);
        }

        private void SumData(int hours, string beiginTime)
        {
            int[] select = bandedGridView1.GetSelectedRows();
            if (select.Length == 0) return;
            int num = bandedGridView1.GetSelectedRows()[0];
            string riqi = bandedGridView1.GetRowCellValue(num, "Date").ToString().Trim();
            int formId = (int)FormType.TempbedNursing;
            string formName = EnumHelper.GetDescription(FormType.TempbedNursing);
            switch (hours)
            {
                case 12:
                    string sql12 = @"if(EXISTS (SELECT Id FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}' ))
                            BEGIN UPDATE NursingFormSumIO SET  Group12 ='Y' WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}' END ELSE BEGIN
                            INSERT INTO NursingFormSumIO (PatientId,VisitId,SumDate,PatientName,BedNo,DepartmentId,DepartmentName,AreaId,AreaName,FormId,FormName,Group12,Group24,GroupDiy,BeginTime)
                            VALUES('{0}','{1}','{2}' ,'{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','Y',NULL,NULL,'{11}') END";
                    sql12 = string.Format(sql12, this.PatientInfo.PATIENT_ID, this.PatientInfo.VISIT_ID, riqi, this.PatientInfo.PATIENT_NAME, this.PatientInfo.BED_NO, this.PatientInfo.DEPARTMENT_ID, this.PatientInfo.DEPARTMENT_NAME, this.PatientInfo.NURSE_CELL_CODE, this.PatientInfo.NURSE_CELL_NAME, formId, formName, beiginTime);
                    SqlHelper.ExecuteNonQuery(sql12);
                    break;
                case 24:
                    string sql24 = @"if(EXISTS (SELECT Id FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}' ))
                            BEGIN UPDATE NursingFormSumIO SET  Group24 ='Y' WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}' END ELSE BEGIN
                            INSERT INTO NursingFormSumIO (PatientId,VisitId,SumDate,PatientName,BedNo,DepartmentId,DepartmentName,AreaId,AreaName,FormId,FormName,Group12,Group24,GroupDiy,BeginTime)
                            VALUES('{0}','{1}','{2}' ,'{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',NULL,'Y',NULL,'{11}') END";
                    sql24 = string.Format(sql24, this.PatientInfo.PATIENT_ID, this.PatientInfo.VISIT_ID, riqi, this.PatientInfo.PATIENT_NAME, this.PatientInfo.BED_NO, this.PatientInfo.DEPARTMENT_ID, this.PatientInfo.DEPARTMENT_NAME, this.PatientInfo.NURSE_CELL_CODE, this.PatientInfo.NURSE_CELL_NAME, formId, formName, beiginTime);
                    SqlHelper.ExecuteNonQuery(sql24);
                    break;
                default:
                    string sqldefault = @"if(EXISTS (SELECT Id FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  ))
                            BEGIN UPDATE NursingFormSumIO SET  GroupDiy ='{12}',BeginTime='{11}' WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  END ELSE BEGIN
                            INSERT INTO NursingFormSumIO (PatientId,VisitId,SumDate,PatientName,BedNo,DepartmentId,DepartmentName,AreaId,AreaName,FormId,FormName,Group12,Group24,BeginTime,GroupDiy)
                            VALUES('{0}','{1}','{2}' ,'{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',NULL,NULL,'{11}','{12}') END";
                    sqldefault = string.Format(sqldefault, this.PatientInfo.PATIENT_ID, this.PatientInfo.VISIT_ID, riqi, this.PatientInfo.PATIENT_NAME, this.PatientInfo.BED_NO, this.PatientInfo.DEPARTMENT_ID, this.PatientInfo.NURSE_CELL_CODE, this.PatientInfo.NURSE_CELL_CODE, this.PatientInfo.NURSE_CELL_NAME, formId, formName, beiginTime, hours);
                    SqlHelper.ExecuteNonQuery(sqldefault);
                    break;
            }
            MessageBox.Show("操作成功");
            LoadOldPatients();
        }
        #endregion

        #region 删除统计
        private void ToolStripMenuItemdelete12_Click(object sender, EventArgs e)
        {
            DeleteSumData(12);
        }

        private void ToolStripMenuItemdelete24_Click(object sender, EventArgs e)
        {
            DeleteSumData(24);
        }

        private void ToolStripMenuItemDiyDel_Click(object sender, EventArgs e)
        {
            DeleteSumData(0);
        }

        private void DeleteSumData(int hours)
        {
            int[] select = bandedGridView1.GetSelectedRows();
            if (select.Length == 0) return;
            int num = bandedGridView1.GetSelectedRows()[0];
            string riqi = bandedGridView1.GetRowCellValue(num, "Date").ToString().Trim();
            string id = bandedGridView1.GetRowCellValue(num, "ID").ToString().Trim();
            if (!string.IsNullOrEmpty(id) && id.IndexOf("-") > 0 && id.Split('-').Length == 3)
                riqi = Convert.ToDateTime(id).ToString("yyyy-MM-dd");
            int formId = (int)FormType.TempbedNursing;
            string formName = EnumHelper.GetDescription(FormType.TempbedNursing);
            switch (hours)
            {
                case 12:
                    string sql12 = @"SELECT Id,Group12,Group24 FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'";
                    sql12 = string.Format(sql12, this.PatientInfo.PATIENT_ID, this.PatientInfo.VISIT_ID, riqi, this.PatientInfo.PATIENT_NAME, this.PatientInfo.BED_NO, this.PatientInfo.DEPARTMENT_ID, this.PatientInfo.DEPARTMENT_NAME, this.PatientInfo.NURSE_CELL_CODE, this.PatientInfo.NURSE_CELL_NAME, formId, formName);
                    DataTable dt = (SqlHelper.ExecuteDataset(sql12, CommandType.Text)).Tables[0];
                    if ((dt.Rows.Count > 0) && (dt.Rows[0]["Group12"].ToString().Contains("Y")))
                    {
                        string sql12_1 = @" UPDATE NursingFormSumIO SET  Group12 ='' WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  ";
                        sql12_1 = string.Format(sql12_1, this.PatientInfo.PATIENT_ID, this.PatientInfo.VISIT_ID, riqi, this.PatientInfo.PATIENT_NAME, this.PatientInfo.BED_NO, this.PatientInfo.DEPARTMENT_ID, this.PatientInfo.DEPARTMENT_NAME, this.PatientInfo.NURSE_CELL_CODE, this.PatientInfo.NURSE_CELL_NAME, formId, formName);
                        SqlHelper.ExecuteNonQuery(CommandType.Text, sql12_1);
                        MessageBox.Show("操作成功");
                    }
                    else
                    {
                        MessageBox.Show("当日未添加统计行");
                    }
                    break;
                case 24:
                    string sql24 = @"SELECT Id,Group12,Group24 FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  ";
                    sql24 = string.Format(sql24, this.PatientInfo.PATIENT_ID, this.PatientInfo.VISIT_ID, riqi, this.PatientInfo.PATIENT_NAME, this.PatientInfo.BED_NO, this.PatientInfo.DEPARTMENT_ID, this.PatientInfo.DEPARTMENT_NAME, this.PatientInfo.NURSE_CELL_CODE, this.PatientInfo.NURSE_CELL_NAME, formId, formName);
                    DataTable dt24 = (SqlHelper.ExecuteDataset(sql24, CommandType.Text)).Tables[0];
                    if ((dt24.Rows.Count > 0) && (dt24.Rows[0]["Group24"].ToString().Contains("Y")))
                    {
                        string sql24_1 = @" UPDATE NursingFormSumIO SET  Group24 ='' WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}' ";
                        sql24_1 = string.Format(sql24_1, this.PatientInfo.PATIENT_ID, this.PatientInfo.VISIT_ID, riqi, this.PatientInfo.PATIENT_NAME, this.PatientInfo.BED_NO, this.PatientInfo.DEPARTMENT_ID, this.PatientInfo.DEPARTMENT_NAME, this.PatientInfo.NURSE_CELL_CODE, this.PatientInfo.NURSE_CELL_NAME, formId, formName);
                        SqlHelper.ExecuteNonQuery(CommandType.Text, sql24_1);
                        MessageBox.Show("操作成功");
                    }
                    else
                    {
                        MessageBox.Show("当日未添加统计行，跨天统计请选择前一天日期操作");
                    }
                    break;
                default:
                    string sqldef = @"SELECT TOP 1 GroupDiy FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  ";
                    sqldef = string.Format(sqldef, this.PatientInfo.PATIENT_ID, this.PatientInfo.VISIT_ID, riqi, this.PatientInfo.PATIENT_NAME, this.PatientInfo.BED_NO, this.PatientInfo.DEPARTMENT_ID, this.PatientInfo.DEPARTMENT_NAME, this.PatientInfo.NURSE_CELL_CODE, this.PatientInfo.NURSE_CELL_NAME, formId, formName);
                    object obj = SqlHelper.ExecuteScalar(sqldef);
                    if (obj != DBNull.Value && obj != null && obj.ToString().Length > 0)
                    {
                        string sqldef_update = @" UPDATE NursingFormSumIO SET GroupDiy=NULL,BeginTime='07:01' WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}' ";
                        sqldef_update = string.Format(sqldef_update, this.PatientInfo.PATIENT_ID, this.PatientInfo.VISIT_ID, riqi, this.PatientInfo.PATIENT_NAME, this.PatientInfo.BED_NO, this.PatientInfo.DEPARTMENT_ID, this.PatientInfo.DEPARTMENT_NAME, this.PatientInfo.NURSE_CELL_CODE, this.PatientInfo.NURSE_CELL_NAME, formId, formName);
                        SqlHelper.ExecuteNonQuery(CommandType.Text, sqldef_update);
                        MessageBox.Show("操作成功");
                    }
                    else
                    {
                        MessageBox.Show("当日未添加统计行，跨天统计请选择前一天日期操作");
                    }
                    break;
            }
            LoadOldPatients();
        }
        #endregion

    }
}